<?php

include './mysqli-driver/autoload.php';
include './RedisDriver.php';
use Library\MysqliDriver;
use Library\MysqliResult;

class Server
{
    private $mysqli;
    private $redis;
    private $serv;
    public function __construct() {
 
    
        // 连接数据库
        $this->mysqli = new MysqliDriver();
        $conf = ['username' => 'pay_system_v5', 'password' => '7DfmZ4MCZ6fWceI8', 'database' => 'pay_system_v5',"host"=>'121.201.110.161'];
        $this->mysqli->connect($conf);
        //redis
        $this->redis = new \RedisDriver();

        $this->serv = new swoole_server("0.0.0.0", 9505);
        $this->serv->set(array(
            'worker_num' => 4,   //一般设置为服务器CPU数的1-4倍
            'daemonize' => 1,  //以守护进程执行
            'max_request' => 10000,
            'dispatch_mode' => 2,
            'task_worker_num' => 8,  //task进程的数量
            "task_ipc_mode " => 3 ,  //使用消息队列通信，并设置为争抢模式
            "log_file" => "log/taskqueueu.log" ,//日志
        ));
        $this->serv->on('Receive', array($this, 'onReceive'));
        $this->serv->on('Task', array($this, 'onTask'));
        $this->serv->on('Finish', array($this, 'onFinish'));
        $this->serv->on('Connect', array($this, 'onConnect'));
        $this->serv->start();


    }
    public function onReceive(  $serv, $fd, $from_id, $data ) {
     
        file_put_contents("form.txt",json_decode($data),FILE_APPEND);
    }
    public function onTask($serv,$task_id,$from_id, $data) {
      
    }
    public function onFinish($serv,$task_id, $data) {
 
    }

    public function onConnect( $serv,  $fd,  $reactorId){
         #$this->sendNotify();
        echo  "已连接";
    }

     /* author@zhou
     * 功能：存储数据到redis
     * return
     */
    public function getData(){

        $time = time() - 7*24*60*60;
        $limit = 100;
        $query = $this->mysqli->query("select pay_bank_account.*,pay_withdraw_money.*,pay_withdraw_money.status from `pay_withdraw_money` left join pay_bank_account  ON pay_bank_account.id = pay_withdraw_money.bank_id where pay_withdraw_money.status  != 0 and pay_withdraw_money.update_time >= {$time} limit {$limit} ");
        $data = $query->result(1);

        $items = [];
        foreach($data as $k=>$v){
            $item = [
                "status" => $v['status'],
                "sn" => $v['sn'],
                "account" => $v['account'],
                "account_name" => $v['account_name'],
                "type" => $v['type'],
                "bank_name" => $v['bank_name'],
                "money" => $v['money'],
                "service_charge" => $v['service_charge'],
                "real_money" => $v['real_money'],
                "add_time" => $v['add_time'],
                "provice"=>$v['provice'],
                "city"=>$v['city'],
                "notify_url"=>$v['notify_url']
            ];

            $msg = '';
            switch ($v['status']) {
                case 0:
                    $msg = "新增";
                    break;
                case 1:
                    $msg = "处理中";
                    break;
                case 2:
                    $msg = "完成";
                    break;
                case 3:
                    $msg = "失败";
                    break;
            }


            $one = ["error_code"=>0,"msg"=>$msg,"data"=>$item];
            $items[$v['sn']] = json_encode($one);
        }


        $key = "notify-url";
        if($items){
            $this->redis->setHash($key, $items);
        }
        echo "SUCCESS";

    }

    /* author@zhou
     * 功能：发送异步通知
     * return 
     */
    public function sendNotify(){

        $key = "notify-url";
        $key2 = "notify-url-num"; //判断次数
        $keyData =$this->redis->hKeys($key);
        if(!$keyData){
            // 触发定时存储数据开关
            $this->getData();
            return;
        }
        $true = true;
        $num = 5;
        $i = 0;
        while($true){
            //判断次数是否大于等于五
            $val = $this->redis->hGet($key2, $keyData[$i]);
            if(!$val || $val <= $num){
                $true = false;
            }
            if(count($keyData) == $i){
                $true = false;
            }
            $i++;
        }

        //最后一条数据次数加限制  暂不加


        //使用队列
        $data = $this->redis->getHash($key,$keyData[$i-1]);
        if($data){

            $arr = json_decode($data[$keyData[$i-1]],true);
            $url = $arr['data']['notify_url'];
            $this->request_post($url,$data[$keyData[$i-1]]);
            $curlNum = $this->redis->hGet($key2, $keyData[$i-1]);
            $curlNum = (int)$curlNum+1;
            $this->redis->hSet($key2,$keyData[$i-1],$curlNum);
            $this->redis->hDel( $key, $keyData[$i-1] );
        }
        echo "SUCCESS";

    }


    public function doJob(){
        $fileContent = file_get_contents('php://input');
        file_put_contents("doJob.txt",$fileContent);
    }


    /* author@zhou
     * 功能：发送数据
     * return 
     */
    public function request_post($url ='',$param ='') {
        $postUrl = $url;
        $curlPost = $param;
        $ch = curl_init();//初始化curl
        curl_setopt($ch, CURLOPT_URL,$postUrl);//抓取指定网页
        curl_setopt($ch, CURLOPT_HEADER, 0);//设置header
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//要求结果为字符串且输出到屏幕上
        curl_setopt($ch, CURLOPT_POST, 1);//post提交方式
        curl_setopt($ch, CURLOPT_POSTFIELDS, $curlPost);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json; charset=utf-8','Content-Length: ' . strlen($curlPost)));
        curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,false);
        curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,false);

        $data = curl_exec($ch);//运行curl
        // var_dump(curl_errno($ch));die;
        curl_close($ch);
        return $data;
    }

}
$server = new Server();
// $server->getData();